package com.cci.kangdao.utilTool;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * @author linjiankun
 * @date 2022/6/7 13:36
 * JWT工具类
 */
public class JWTTool {

	private static Logger log = Logger.getLogger(JWTTool.class);

	//token秘钥
	private static final String TOKEN_SECRET = "cty-kangDaoApi";


	public static String getToken (String username){
		String token = "";
		try {
			//秘钥及加密算法
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			//设置头部信息
			Map<String,Object> header = new HashMap<>();
			header.put("typ","JWT");
			header.put("alg","HS256");
			//携带username信息，生成签名
			token = JWT.create()
					.withHeader(header)
					.withClaim("username",username).withClaim("timestamp",System.currentTimeMillis())
					.sign(algorithm);
		}catch (Exception e){
			log.error("JWT生成token异常,异常用户："+ username +"，异常原因："+e.getMessage(),e);
			return token;
		}
		return token;
	}

	public static boolean verifyToken(String token){
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			DecodedJWT jwt = verifier.verify(token);
			System.out.println(jwt.getClaim("username").asString());
			return true;
		}catch (Exception e){
			log.error("JWT验证token异常，异常原因："+e.getMessage(),e);
			return  false;
		}
	}


	public static DecodedJWT getDecodedJWTByToken(String token){
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			return verifier.verify(token);
		}catch (Exception e){
			log.error("JWT验证token异常，异常原因："+e.getMessage(),e);
			return null;
		}
	}



	

	public static void main(String[] args) {
		//手机号当作用户名
		String username ="15230112379";
		//生成token
		String token = getToken(username);
		System.out.println(token);
		//验证token
		boolean b = verifyToken(token);
		System.out.println(b);
	}
}

